package com.example.demo.model;


import com.example.demo.core.exception.ProgramException;

import java.util.LinkedHashMap;
import java.util.Map;


/**
 * 利用LinkedHashMap实现LRU算法
 * @author yj
 * @date 2021/3/26 10:46
 */
public class LinkedBaseMap<K, V> extends LinkedHashMap<K, V> implements Map<K, V> {

    private Integer maxSize;

    /**
     * @param initialCapacity 初始大小
     * @param loadFactor      阔载因子
     * @param accessOrder     值为true时，表示按照访问顺序迭代；值为false时，表示按照插入顺序迭代
     */
    public LinkedBaseMap(int initialCapacity, float loadFactor, boolean accessOrder) {
        super(initialCapacity, loadFactor, accessOrder);
        this.maxSize = 0;
    }

    /**
     * @param initialCapacity 初始大小
     * @param loadFactor      阔载因子
     */
    public LinkedBaseMap(int initialCapacity, float loadFactor) {
        super(initialCapacity, loadFactor);
        this.maxSize = 0;
    }

    /**
     * @param accessOrder     值为true时，表示按照访问顺序迭代；值为false时，表示按照插入顺序迭代
     */
    public LinkedBaseMap(boolean accessOrder) {
        super(16, 0.75f, accessOrder);
        this.maxSize = 0;
    }

    /**
     * initialCapacity  初始化大小
     * loadFactor  加载因子
     * accessOrder  顺序标签，true时会把get和put的值移到末尾，false时不处理
     */
    public LinkedBaseMap() {
        super(16, 0.75f, true);
        this.maxSize = 0;
    }

    public LinkedBaseMap(int initialCapacity) {
        super(initialCapacity, 0.75f, true);
        this.maxSize = 0;
    }

    /**
     * 最大存储数
     *
     * @param maxSize 必须大于0的正整数
     */
    public LinkedBaseMap(Integer maxSize) {
        super(16, 0.75f, true);
        setMaxSize(maxSize);
    }

    public void setMaxSize(Integer maxSize){
        if (maxSize <= 0) {
            throw new ProgramException("最大参数不对");
        }
        this.maxSize = maxSize;
    }

    /**
     * 重写LinkedHashMap中的removeEldestEntry方法，当Map中元素超过{@link this#maxSize}时自动删除最常使用的元素，
     */
    @Override
    protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
        if (maxSize == 0) {
            return false;
        }
        return size() > maxSize;
    }


}